package cn.tanghom.app.oa.service;

import java.util.Date;

import javax.annotation.Resource;

import lombok.val;

import org.flowable.engine.delegate.BpmnError;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.JavaDelegate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.tanghom.app.oa.model.Candidate;
import cn.tanghom.app.oa.model.Employee;
import cn.tanghom.app.oa.repository.CandidateRepository;
import cn.tanghom.app.oa.repository.EmployeeRepository;
import cn.tanghom.app.oa.repository.PositionRepository;
import cn.tanghom.app.oa.repository.TalentRepository;

/**
 * 创建新员工
 * @author Hunteron-cp
 *
 */
@Service
public class EmployeeProcessDelegate implements JavaDelegate {
  @Resource
  private PositionRepository positionRespository;
	
  @Autowired
  private TalentRepository talentRepository;
  
  @Autowired
  private CandidateRepository candidateRepository;
  
  @Autowired
  private EmployeeRepository employeeRepository;

  @Override
  public void execute(DelegateExecution execution) {
  
    Boolean matched = (Boolean)execution.getVariable("matched");
    if(matched){
    	Candidate candidate = (Candidate)execution.getVariable("candidate");	  
	    if(candidate==null){
	    	execution.setTransientVariable("errorMessage", "candidate not existed!");
	    	throw new BpmnError("BusinessExceptionOccurred");
	    	//return ;
	    }	    
	    
	    Employee employee = createEmployee(candidate);
	   
	    execution.setVariable("employee", employee);	   
	    
	    System.out.println("Faux call to backend for ["  + employee + "]");
	    
    }
  }
  
  
  
  public Employee createEmployee(Candidate candidate) {
    Date now = new Date();  
    if(candidate!=null){	   
    	val position = positionRespository.findOne(candidate.getPositionId());
	    val talent = talentRepository.findOne(candidate.getTalentId());
	    Employee employee = new Employee();
	    employee.setDepName(talent.getCategoryName());
	    employee.setTalentId(candidate.getTalentId());
	    employee.setCreateTime(now);
	    employee.setEmail(talent.getEmail());
	    employee.setEmpName(talent.getName());
	    
	    employee.setSalary(position.getAnnualSalary());
	    employee.setSubTitleId(position.getSubTitleId());
	    
	    employeeRepository.save(employee);
	    return employee;
    }
    return null;
  }

}
 